import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Alert,
    FlatList,
    TextInput,
    Linking,
    Image,
    DeviceEventEmitter,
    ScrollView
} from 'react-native';

import moment from 'moment';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import AndroidModule from "../../utils/AndroidConnent";
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import NoData from '../../utils/NoData'
import Loading from "../../utils/Loading";
import { getImgUrl } from '../../utils/ComFunction'
import Header from "../../components/header";
import LinearGradient from 'react-native-linear-gradient';


const screenW = Dimensions.get('window').width;
const colorsOptions = ['#ED542E', '#2CE454', '#2CE454', '#ff6600', '#ED542E']

let navigation

export default class ContractDetailPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            contractNo: this.props.route.params.contractNo,
            orderNo: this.props.route.params.orderNo,
            data: {}
        }
    }

    componentDidMount() {
        this.getContractDetail()
    }

    getContractDetail() {
        this.Loading.show();
        HttpUtils.getRequest(HttpUrls.getContractByNo, { contractNo: this.state.contractNo })
            .then((result) => {
                console.log('contractDetail', result.data);
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    this.setState({
                        data: result.data
                    })

                   

                    // /participantMerchantId

                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    render() {
        navigation = this.props.navigation;
        let data = this.state.data
        let allOnes = this.state.data.contractStatus === 1
        return (
            <View style={styles.container}>
                <Header navigation={navigation} hideSepLine={true} Title={'合同详情'} ></Header>
                <ScrollView style={{ flex: 1, paddingTop: 10, paddingHorizontal: 8 }}>
                    <View style={styles.contractBox}>
                        <View style={styles.topBox}>
                            <Text style={styles.contractTitleText}>{'电子合同-' + (Constant.userInfo.isFranchisee == 1 ? '销售' : '购买') + (data.contractNo ? data.contractNo : '')}</Text>

                            {/* <Text style={styles.contractStatusText}>{this.getContractStatusText()}</Text> */}

                        </View>
                        <Text style={styles.contractText}>{data.contractName ? data.contractName : "未填写合同名称"}</Text>
                        <View style={{ marginTop: 10, flexDirection: 'row', alignItems: 'center' }}>
                            <Text style={{ color: '#999999', fontSize: 14 }}>发起:</Text>
                            <Text style={styles.startText}>{data.initiatorUserName} ({data.initiatorMerchantName})</Text>
                        </View>
                        <View style={styles.commonbuttwen}>
                            <Text style={styles.commonTitle}>时间：</Text>
                            <Text style={styles.commonValue}>{this.getcreateTime(data.initiatorTime)}</Text>
                        </View>

                        {/* {
                            data.contractSignersInfo && data.contractSignersInfo.length > 0 ?
                                <View style={[styles.commonbuttwen, { flexWrap: 'wrap', flex: 1, marginEnd: 10 }]}>
                                    {
                                        this.getStatusList(data.contractSignersInfo).map((itemInfo, index) => {
                                            let colorStatus = colorsOptions[itemInfo.signStatus]
                                            return (
                                                <View style={{ flexDirection: 'row', marginRight: 10, alignItems: 'center' }} key={index}>
                                                    <Text style={[styles.commonTitle, { color: colorStatus }]}>{this.getStatusTitle(itemInfo.signStatus)}:</Text>
                                                    <Text style={styles.commonValue}>{itemInfo.title}</Text>
                                                </View>
                                            )
                                        })


                                    }

                                </View>
                                :
                                null
                        } */}

                        {/* 车辆相关 */}
                        {
                            data.bizInfo && JSON.parse(data.bizInfo).carName
                                ?
                                <TouchableOpacity
                                    style={styles.carInfoBox}
                                    onPress={() => {
                                        navigation.navigate('CarDetailPage', { carId: JSON.parse(data.bizInfo).carId,merchantId:this.state.data.participantMerchantId })
                                    }}
                                >
                                    {
                                        JSON.parse(data.bizInfo).mainPic
                                            ?
                                            <Image style={styles.carImg}
                                                source={{ uri: getImgUrl(JSON.parse(data.bizInfo).mainPic) }}></Image>
                                            :
                                            <Image source={require('source/image/electron/carpic.png')} style={styles.carImg} />
                                    }

                                    <View style={styles.carBox}>
                                        <Text style={styles.brandText} numberOfLines={1}>{JSON.parse(data.bizInfo).carName.replaceAll('#', ' ')}</Text>
                                        <Text style={styles.vinText}>{JSON.parse(data.bizInfo).vcode ? ('VIN:' + JSON.parse(data.bizInfo).vcode.toUpperCase()) : ''}</Text>
                                    </View>
                                </TouchableOpacity>
                                :
                                null
                        }
                    </View>
                    <View style={[styles.contractBox, { marginTop: 10 }]}>
                        <Text style={styles.signText}>签署方</Text>
                        {
                            data.contractSignersInfo ?
                                data.contractSignersInfo.map((item, index) => {
                                    return (
                                        <View style={[styles.signBox, { marginBottom: index == data.contractSignersInfo.length - 1 ? 16 : 10 }]} key={index}>
                                            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                                <Text style={styles.signerText}>{item.participantFlag}</Text>
                                                <View style={styles.singerTypeBox}>
                                                    <Text style={styles.signerTypeText}>{item.participantType == '1' ? '企业' : '个人'}</Text>
                                                </View>
                                            </View>
                                            {
                                                item.orgName && item.orgName != '' ?
                                                    <Text style={styles.signerText1}>{item.orgName}</Text>
                                                    :
                                                    null
                                            }

                                            {/* {
                                                item.orgDrafter && item.orgDrafter.transactor ?
                                                    <Text style={styles.signerText1}>{item.orgDrafter.transactor.transactorName + item.orgDrafter.transactor.transactorPsnAccount}</Text>
                                                    :
                                                    
                                            } */}
                                            <Text style={styles.signerText1}>{item.transactorName + ' ' + item.transactorPsnAccount}</Text>

                                            <Text style={[styles.signStatusText,{color:item.signStatus == 1 || item.signStatus == 0 ? '#F99802' : '#6ECC49'}]}>{this.getDraftStatusTitle(item.signStatus)}</Text>
                                        </View>
                                    )
                                })
                                :
                                null
                        }
                    </View>
                </ScrollView>

                <View style={{ width: '100%', flexDirection: 'column', backgroundColor: '#fff', height: 60 + Constant.bottomHeight }}>
                    <View style={styles.bottomBox}>
                        {/**0 - 草稿 1 - 签署中 2 - 完成签署 3 - 已废弃 5 - 已过期 7 -已拒签 9-合同拟定中 10-解约中 11-部分已解约 12-已解约 20-发起签署失败	*/}
                        {this.state.data.contractStatus == 1 || this.state.data.contractStatus == 2 || this.state.data.contractStatus == 10
                            || this.state.data.contractStatus == 12 ?
                            <TouchableOpacity
                                style={styles.lookContractBtn}
                                onPress={() => {
                                    this.checkContract()
                                }}
                            >
                                <Text style={styles.signBottomText}>查看合同</Text>
                            </TouchableOpacity>
                            :
                            null
                        }

                        {/* {this.state.data.contractStatus == 1 ?
                            <TouchableOpacity
                                style={styles.signBtn}
                                onPress={() => {
                                    this.signContract()
                                }}
                            >
                                <Text style={styles.signBottomText}>立即签署</Text>
                            </TouchableOpacity>
                            : null
                        } */}
                        {this.state.data.contractStatus == 0 || this.state.data.contractStatus == 9 || this.state.data.contractStatus == 1 ?
                            <TouchableOpacity
                                style={styles.signBtn}
                                onPress={() => {
                                    // if (this.state.data.contractStatus == 0 || this.state.data.contractStatus == 9) {
                                    //     ToastToUser('合同拟定中')
                                    //     return
                                    // }
                                    this.signContract()
                                }}
                            >
                                <Text style={styles.signBottomText}>{this.state.data.contractStatus == 0 || this.state.data.contractStatus == 9 ? '拟定合同' : '签署合同'}</Text>
                            </TouchableOpacity>
                            :
                            null
                        }


                    </View>
                </View>

                <Loading onRef={(ref) => (this.Loading = ref)} />
            </View>
        )
    }

    getContractStatusText() {
        let contractStatus = this.state.data.contractStatus
        let contractSignersInfo = this.state.data.contractSignersInfo

        if (contractStatus == 0) {
            return '合同拟定中'
        } else if (contractStatus == 1) {
            let initiatorMerchantId = this.state.data.initiatorMerchantId
            // if(initiatorMerchantId == Constant.userInfo.merchantId){
            //     //判断我方是否签署
            //     contractSignersInfo.map((item, index) => {
            //         if(item.signStatus == 2){
            //             return '待我签署'
            //         }
            //     })

            // }else{
            //     return '待对方签署'
            // }
        }
    }

    // 点击查看合同
    checkContract() {

        if (this.Loading) {
            this.Loading.show();
        }

        let param = {
            contractNo: this.state.contractNo,
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
        }

        HttpUtils.getRequest(HttpUrls.downloadPdf, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }

                let code = result.code

                if (code == 0) {


                    Linking.openURL(result.data).catch(err => console.error('An error occurred', err));

                } else {
                    ToastToUser(result.msg + '')
                }
            })
            .catch((error) => {

            });

    }

    getrightshow(temp) {
        if (temp == 2) {
            return '完成签署'
        } else if (temp == 3) {
            return '已废弃'
        } else if (temp == 5) {
            return '已过期'
        } else if (temp == 7) {
            return '已拒签'
        } else if (temp == 10) {
            return '解约中'
        } else if (temp == 11) {
            return '部分已解约'
        } else if (temp == 12) {
            return '已解约'
        } else {
            return ''
        }
    }

    getcreateTime(time) {
        return moment(time).format("YYYY-MM-DD HH:mm")
    }

    //通过状态获取标题
    getStatusTitle(status) {
        if (status == 0) {
            return '待签'
        } else if (status == 1) {
            return '签署中'
        } else if (status == 2) {
            return '已签'
        } else if (status == 3) {
            return '等待审批'
        } else if (status == 4) {
            return '已拒签'
        }
    }

    /**
     * 0 - 等待签署 ，1 - 签署中，2 - 已签署，3 - 等待审批，4 - 已拒签	是	[string]
     * 
     */
    getDraftStatusTitle(status) {
        if (status == 0) {
            return '待签署'
        } else if (status == 1) {
            return '签署中'
        } else if (status == 2) {
            return '已签署'
        } else if (status == 3) {
            return '等待审批'
        } else if (status == 4) {
            return '已拒签'
        } else if (status == 5) {
            return '已过期'
        }
    }

    getStatusList(temp) {
        const result = [];
        const statusMap = {};
        temp.forEach(item => {
            const transactorName = item.psnName || item.transactorName
            const { signStatus } = item;

            // 如果状态已经存在于 statusMap 中，则追加名称
            if (statusMap[signStatus]) {
                statusMap[signStatus].push(transactorName);
            } else {
                // 否则，创建新的状态条目
                statusMap[signStatus] = [transactorName];
            }
        });

        for (const [signStatus, names] of Object.entries(statusMap)) {
            result.push({
                signStatus: signStatus,
                title: names.join(',') // 将名称数组转换为字符串
            });
        }

        return result

    }


    signContract() {

        if (this.Loading) {
            this.Loading.show();
        }

        let param = {
            bizId: this.state.data.bizId,
            bizType: 3,
            participantFlag: Constant.userInfo.isFranchisee == 1 ? '卖方' : '买方',
        }

        HttpUtils.postRequest(HttpUrls.getSignUrlByCarOrderNo, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }

                let code = result.code

                if (code == 0) {

                    Linking.openURL(result.data).catch(err => console.error('An error occurred', err));

                } else {
                    ToastToUser(result.msg + '')
                }
            })
            .catch((error) => {

            });

    }


}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    contractBox: {
        backgroundColor: '#fff',
        borderRadius: 6,
        paddingHorizontal: 16,
    },
    topBox: {
        width: '100%',
        height: 44,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        borderBlockColor: '#E4E4E4',
        borderBottomWidth: 0.5
    },
    contractTitleText: {
        fontSize: 14,
        color: '#333'
    },
    contractStatusText: {
        fontSize: 14,
        fontWeight: '500',
        color: '#ED542E'
    },
    contractStatusComplete: {
        fontWeight: '500',
        fontSize: 14,
        color: '#2CE454',
    },
    contractText: {
        marginTop: 14,
        fontSize: 14,
        fontWeight: '500',
        color: '#333333'
    },
    startText: {
        marginLeft: 5,
        fontSize: 14,
        color: '#333'
    },
    commonbuttwen: {
        marginTop: 10,
        flexDirection: 'row'
    },

    commonTitle: {
        fontWeight: '400',
        fontSize: 14,
        color: '#999999',
    },

    commonValue: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
        marginLeft: 5
    },

    carInfoBox: {
        marginVertical: 12,
        padding: 12,
        backgroundColor: '#F4F4F4',
        borderRadius: 8,
        width: '100%',
        height: 76,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start'
    },
    carImg: {
        width: 52,
        height: 52
    },
    carBox: {
        marginLeft: 12,
        flex: 1,
        flexDirection: 'column',
        alignItems: 'flex-start',
        justifyContent: 'center'
    },
    brandText: {
        fontSize: 14,
        color: '#333333'
    },
    vinText: {
        marginTop: 8,
        fontSize: 14,
        color: '#333333'
    },
    bottomBox: {
        width: '100%',
        height: 60,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 12,
    },
    signText: {
        marginTop: 18,
        marginBottom: 12,
        fontSize: 16,
        fontWeight: '500',
        color: '#333'
    },
    signBox: {
        backgroundColor: '#F4F4F4',
        borderRadius: 8,
        padding: 12,
        flexDirection: 'column',
        justifyContent: 'center'
    },
    signerText: {
        fontSize: 14,
        fontWeight: '500',
        color: '#333333'
    },
    singerTypeBox: {
        marginLeft: 5,
        paddingHorizontal: 6,
        height: 20,
        borderRadius: 3,
        borderWidth: 1,
        borderColor: '#0052D9',
        alignItems: 'center',
        justifyContent: 'center'
    },
    signerTypeText: {
        fontSize: 12,
        color: '#0052D9'
    },
    signerText1: {
        fontSize: 14,
        color: '#333333',
        marginTop: 6
    },
    signStatusText: {
        position: 'absolute',
        right: 12,
        color: '#6ECC49',
        fontSize: 14,
        fontWeight: '500'
    },

    lookContractBtn: {
        height: 36,
        flex: 1.2,
        backgroundColor: '#F5F5F5',
        borderRadius: 18,
        justifyContent: 'center',
        alignItems: 'center'
    },
    signBtn: {
        marginLeft: 12,
        height: 36,
        flex: 2,
        backgroundColor: '#FFE000',
        borderRadius: 18,
        justifyContent: 'center',
        alignItems: 'center',
    },
    signBottomText: {
        fontSize: 14,
        color: '#222'
    }

})